package com.gsy.aop;

import com.gsy.aop.annotation.TokenValid;
import com.gsy.constant.GlobalConstant;
import com.gsy.exception.TokenErrorException;
import com.gsy.request.BaseRequest;
import com.gsy.utils.JsonUtils;
import com.gsy.utils.JwtUtils;
import com.gsy.utils.RedisCacheUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Map;

/**
 * 参数验证
 */
@Aspect
@Component
@SuppressWarnings("static-method")
public class TokenValidAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(TokenValidAspect.class);



    @Pointcut("@annotation(com.gsy.aop.annotation.TokenValid)")
    public void valid() {
    }

    /**
     * 验证处理
     *
     * @param joinPoint
     * @throws Exception
     */
    @Before("valid()")
    public void validProcess(JoinPoint joinPoint) throws Exception {
//        Object[] args = joinPoint.getArgs();
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        Method method = signature.getMethod();
//        TokenValid valid = method.getAnnotation(TokenValid.class);
//        int position = valid.position();
//        if (args.length - 1 < position) {
//            throw new IllegalArgumentException("illegal ParameterValid's postion value beyond method's args length");
//        }
//        Object thisObject = args[position];
//        if (thisObject == null) {
//            throw new IllegalArgumentException("parameter is null");
//        }
//        String requestJson = thisObject.toString();
//        if (StringUtils.isBlank(requestJson)) {
//            throw new IllegalArgumentException("parameter is null");
//        }
////        String apiName = valid.apiName();
////        BaseRequest request = null;
////        try {
////            request = JsonUtils.parse(requestJson, valid.formatObj());
////        } catch (Exception e) {
////            LOGGER.error(MessageFormat.format("转换接口{0}请求数据异常", apiName), e);
////        }
////        if (request == null) {
////            throw new IllegalArgumentException("转换接口请求数据异常");
////        }
////        Class<?> clazz = null;
////        try {
////            clazz = Class.forName(request.getClass().getName());
////        } catch (ClassNotFoundException e) {
////            LOGGER.error("对象加载异常，异常信息={}", e.getMessage());
////            return;
////        }
        HttpServletRequest request1 = null;
        try {

            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            assert requestAttributes != null;
            request1 = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        }catch (Exception e){
            LOGGER.error("对象加载异常");
        }
        if (request1 == null){
            throw new TokenErrorException("对象加载异常！");
        }

        String accessToken = request1.getHeader("Authorization") == null ? "" : request1.getHeader("Authorization");
        LOGGER.info("accessToken is {}", accessToken);
        if (StringUtils.isNotBlank(accessToken)) {
            String[] split = accessToken.split("Bearer ");
            accessToken = split[1];
        }

        Map<String, Object> userInfo = JwtUtils.verity(accessToken);
//         Long userId = JwtUtils.verity(access_token);
        Long userId = Long.valueOf(String.valueOf(userInfo.get("userId")));
        if (!RedisCacheUtils.hasKey(GlobalConstant.SESSION_LOGIN_KEY+userId)){
            throw new TokenErrorException("登录已过期，请重新登录！");
        }
        RedisCacheUtils.putCache(GlobalConstant.SESSION_LOGIN_KEY+userId,userId,60*60*24);

    }

}
